<?php

require_once 'BasicController.php';

class BoughtController extends Zend_Controller_Action
{

	public function init()
	{
		$ad = new AdminBusiness();
		$user = Zend_Auth::getInstance()->getStorage()->read();
		$this->view->user = $user;


		if(isset($user) && $user != null){
			$cartBusiness = new CartBusiness();
			$this->view->shopping_count = $cartBusiness->countItems($user['idClient']);

		}

		$this->view->enterprises = $ad->getAllEnterprises();
		$this->view->categories = $ad->getAllCategories();
	}

	//ACTION QUE RECEBE OS DADOS PARA SEREM ENVIADOS AO PAGSEGURO
	public function indexAction(){
		$clientBusiness = new ClientBusiness();
		$cartBusiness = new CartBusiness();
		$config = new Zend_Config_Ini('../application/configs/application.ini', 'production');

		if ($_POST){
			$shippingType = $this->_request->getParam('shippingType');
			$receiver = $this->_request->getParam('receptor');
			$deliveryHour = $this->_request->getParam('deliveryHour');
			
			$paymentRequest = new PagSeguroPaymentRequest();
			$paymentRequest->setCurrency("BRL");
			$user = Zend_Auth::getInstance()->getStorage()->read();

			$cart = $cartBusiness->getCart($user['idClient']);

			$sender = $clientBusiness->getUserByid($user['idClient']);

			foreach ($cart as $item){

				$weight = $item['weight']*1000;

				if($weight < 300){
					$weight = 300;
				}

				if($shippingType == 3){
					$weight = 0;
				}

				$paymentRequest->addItem(
				Array(
						'id' => $item['id_product'], 
						'description' =>$item['name'], 
						'quantity' =>$item['qtd'], 
						'amount' => $item['price'],
						'weight' => $weight,
				)
				);
			}

			//SETA OS DADOS DO COMPRADOR
			$paymentRequest->setSender(
			$sender['name'],
			$sender['email'],
			substr($sender['phone'], 1 , 2),
			str_replace("-", "",substr($sender['phone'], 4))
			);

			//SETA OS DADOS DO ENDEREÇO DE ENVIO
			$data = Array(
			    'postalCode' => str_replace("-", "",$this->_request->getParam('cepShip')) ,  
			    'street' => utf8_decode($this->_request->getParam('addressShip')),  
			    'number' => $this->_request->getParam('numberShip'),  
			    'complement' => utf8_decode($this->_request->getParam('compShip')),  
			    'district' => utf8_decode($this->_request->getParam('neighShip')),  
			    'city' => utf8_decode($this->_request->getParam('cityShip')),  
			    'state' => utf8_decode(strtoupper($this->_request->getParam('stateShip'))),  
			    'country' => "Brasil"  
			    );
			    
			    $address = new PagSeguroAddress($data); // objeto PagSeguroAddress

			    $shipping = new PagSeguroShipping();

			    $shipping->setAddress($address);

			    $paymentRequest->setShipping($shipping);

			    $paymentRequest->setShippingType($shippingType);

			    //SE A ENTREGA FOR EM ARARAQUARA ADICIONAR UM FRETE DE R$5,00
			    if($shippingType == 3){
			    	$paymentRequest->setShippingCost(number_format($config->shipping->cost, 2));

			    	//SALVA ARQUIVO COM DADOS DE FRETE PARA ARAQUARA
			    	$arquivo = fopen('../delivery/'.$user['idClient'].'.txt','w+');
			    	if ($arquivo == false){
			    		die('Não foi possível criar o arquivo.');
			    	}else{
			    		fwrite($arquivo, $deliveryHour.'|'.$receiver);
			    		fclose($arquivo);
			    	}
			    }

			    //$paymentRequest->setMaxAge(172800); // 2 dias

			    $paymentRequest->setReference(md5(date("d/m/y h:i:s")).$user['idClient']);

			    $credentials = new PagSeguroAccountCredentials($config->pagSeguro->email, $config->pagSeguro->token);

			    $url = $paymentRequest->register($credentials);

			    $paymentRequest->setRedirectURL($config->pagSeguro->return);

			    $this->_redirect($url);
		}

	}

	public function searchTransactionAction(){

		$clientBusiness = new ClientBusiness();

		$transactionBusiness = new TransactionBusiness();

		$config = new Zend_Config_Ini('../application/configs/application.ini', 'production');

		$credentials = new PagSeguroAccountCredentials($config->pagSeguro->email, $config->pagSeguro->token);

		$initial_date = date("Y-m-d\TH:i", strtotime("-30 days"));

		$final_date = date("Y-m-d\TH:i");

		$maxPageResults = 100;

		$pageNumber = 1;

		LogPagSeguro::info("Preparando para atualização transações por data");
		//Realizando a consulta das transações por data
		$result = PagSeguroTransactionSearchService::searchByDate(
		$credentials,
		$pageNumber,
		$maxPageResults,
		$initial_date,
		$final_date
		);

		$transactions = $result->getTransactions();

		foreach ($transactions as $transaction) {

			try{
				LogPagSeguro::info("Iniciando transação ".$transaction->getCode()."por data");
				$transact = PagSeguroTransactionSearchService::searchByCode(
				$credentials,
				$transaction->getCode()
				);

				$oldTransaction = $transactionBusiness->getTransactionById($transaction->getCode());

				if($oldTransaction){

					$data = array(
					'date_update' => $transact->getLastEventDate(),
					'status' => $transact->getStatus()->getValue(),
					);

					$transactionBusiness->updateTransaction($data, $transaction->getCode());
					LogPagSeguro::info("Transação ".$transaction->getCode()." atualizada com sucesso");

				}else{

					$client = $clientBusiness->getUserByEmail($transact->getSender()->getEmail());

					$data = array(
					'id_transaction' => $transaction->getCode(),
					'id_client' => $client['id_client'],
					'date' => $transact->getDate(),
					'date_update' => $transact->getLastEventDate(),
					'status' => $transact->getStatus()->getValue(),
					);

					$payment = array(
					'id_transaction' => $transaction->getCode(),
					'id_payment' => $transact->getPaymentMethod()->getCode()->getValue(), 
					);

					$transactionBusiness->newTransaction($data);

					$transactionBusiness->savePaymentType($payment);

					foreach ($transact->getItems() as $item){
						$dataProd = array(
					'id_transaction' => $transaction->getCode(),
					'id_product' => $item->getId(),
						);

						$cartMirror = array(
					'id_transaction' => $transaction->getCode(),
					'id_product' => $item->getId(),
					'id_client' => $client['id_client'],
					'qtd' => $item->getQuantity(),
						);

						$transactionBusiness->saveProducts($dataProd);

						$transactionBusiness->saveCartMirror($cartMirror);
					}

					LogPagSeguro::info("Transação ".$transaction->getCode()." recebida com sucesso");
				}
				LogPagSeguro::info("Finalizando transação ".$transaction->getCode());
			}catch (Exception $e){
					
			}
		}

	}

	//RECEBE UM OCORRENCIA QUANDO HÁ ALTERAÇÃO EM ALGUMA TRANSAÇÃO
	public function occurenceAction(){
		$config = new Zend_Config_Ini('../application/configs/application.ini', 'production');
		$transactionBusiness = new TransactionBusiness();


		LogPagSeguro::info("Recebendo notificações automáticas");
		if (count($_POST) > 0) {
			LogPagSeguro::info("teste post".sizeof($_POST)."count".count($_POST));

			// POST recebido, indica que é a requisição do NPI.
			$result = $this->notificationPost($config->pagSeguro->token);

			$transacaoID = isset($_POST['TransacaoID']) ? $_POST['TransacaoID'] : '';

			if ($result == "VERIFICADO") {
				LogPagSeguro::info("Verificado Recebendo notificações automáticas".$transacaoID);
				//O post foi validado pelo PagSeguro.
			} else if ($result == "FALSO") {
				LogPagSeguro::info("Falso Recebendo notificações automáticas".$transacaoID);
				//O post não foi validado pelo PagSeguro.
			} else {
				LogPagSeguro::info("Erro Recebendo notificações automáticas".$transacaoID);
				//Erro na integração com o PagSeguro.
			}

		}else{
			LogPagSeguro::info("Post não recebido");
		}


	}

	public function notificationPost($token) {
		$postdata = 'Comando=validar&Token='.$token;
		foreach ($_POST as $key => $value) {
			$valued    = $this->clearStr($value);
			$postdata .= "&$key=$valued";
		}
		return $this->verify($postdata);
	}

	private function clearStr($str) {
		if (!get_magic_quotes_gpc()) {
			$str = addslashes($str);
		}
		return $str;
	}

	private function verify($data) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, "https://pagseguro.uol.com.br/pagseguro-ws/checkout/NPI.jhtml");
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		$result = trim(curl_exec($curl));
		curl_close($curl);
		return $result;
	}

	//ACTION DE RETORNO QUANDO É FINALIZADA UMA COMPRA
	public function returnAction(){

		$user = Zend_Auth::getInstance()->getStorage()->read();
		$transactionBusiness = new TransactionBusiness();
		$cartBusiness = new CartBusiness();

		$config = new Zend_Config_Ini('../application/configs/application.ini', 'production');
		$credentials = new PagSeguroAccountCredentials($config->pagSeguro->email, $config->pagSeguro->token);

		try{
			if(isset($user) && $user != null){

				$cartBusiness = new CartBusiness();
				$clientBusiness = new ClientBusiness();
				$shopping_cart = $cartBusiness->getCart($user['idClient']);

				$transaction_id = $this->_request->getParam('transaction_id');

				LogPagSeguro::info("Transação id :".$transaction_id." recebida com sucesso.");

				$transaction = PagSeguroTransactionSearchService::searchByCode(
				$credentials,
				$transaction_id
				);


				$client = $clientBusiness->getUserByid($user['idClient']);

				$oldTransaction = $transactionBusiness->getTransactionById($transaction_id);
				
				//VERIFICA SE A TRANSAÇÃO EXISTE NO SISTEMA
				//CASO EXISTA FAZ O UPDATE DELA				
				if($oldTransaction){
					LogPagSeguro::info("Efetudando update da transação :".$transaction_id);

					$data = array(
					'date' => $transaction->getDate(),
					'status' => $transaction->getStatus()->getValue(),
					'grossAmount' 		=> $transaction->getGrossAmount(),
					'netAmount'			=> $transaction->getNetAmount(),
					'discountAmount'	=> $transaction->getDiscountAmount(),
					'feeAmount'			=> $transaction->getFeeAmount(),
					'extraAmount'		=> $transaction->getExtraAmount(),
					'shippingCost'		=> $transaction->getShipping()->getCost(),
					);

					$transactionBusiness->updateTransaction($data, $transaction->getCode());

				}else{

					LogPagSeguro::info("Preparando para inserir transação :".$transaction_id);

					$delivery = null;
					
					//VERIFICA SE EXISTE O ARQUIVO DE DETALHE(VÁLIDO SOMENTE PARA COMPRAS NA CIDADE)
					if(file_exists('../delivery/'.$user['idClient'].'.txt')){
						$arquivo = fopen('../delivery/'.$user['idClient'].'.txt','r');
						if ($arquivo == true){
							$linha = fgets($arquivo);
							$delivery = explode("|", $linha);
							fclose($arquivo);
							unlink('../delivery/'.$user['idClient'].'.txt');
						}
					}

					//MONTA O ARRAY COM OS DADOS DA TRANSAÇÃO VINCULADOS AO CLIENTE
					$data = array(
					'id_transaction' 	=> $transaction_id,
					'id_client' 		=> $client["id_client"],
					'date'				=> $transaction->getDate(),
					'date_update' 		=> $transaction->getLastEventDate(),
					'status' 			=> $transaction->getStatus()->getValue(),
					'grossAmount' 		=> $transaction->getGrossAmount(),
					'netAmount'			=> $transaction->getNetAmount(),
					'discountAmount'	=> $transaction->getDiscountAmount(),
					'feeAmount'			=> $transaction->getFeeAmount(),
					'extraAmount'		=> $transaction->getExtraAmount(),
					'shippingCost'		=> $transaction->getShipping()->getCost(),
					);

					//MONTA O ARRAY COM OS DADOS DA TRANSAÇÃO VINCULADOS AO CLIENTE + DADOS DO ARQUIVO DE DETALHE(VÁLIDO SOMENTE PARA COMPRAS NA CIDADE)
					if($delivery){
						$data = array(
							'id_transaction' 	=> $transaction_id,
							'id_client' 		=> $client["id_client"],
							'date'				=> $transaction->getDate(),
							'date_update' 		=> $transaction->getLastEventDate(),
							'status' 			=> $transaction->getStatus()->getValue(),
							'grossAmount' 		=> $transaction->getGrossAmount(),
							'netAmount'			=> $transaction->getNetAmount(),
							'discountAmount'	=> $transaction->getDiscountAmount(),
							'feeAmount'			=> $transaction->getFeeAmount(),
							'extraAmount'		=> $transaction->getExtraAmount(),
							'shippingCost'		=> $transaction->getShipping()->getCost(),
							'delivery_hour' => utf8_decode($delivery[0]),
							'receiver' => utf8_decode($delivery[1])
						);
					}

					//MONTA O ARRAY COM OS DADOS DE ENTREGA
					$transactionAdrress = array(
					'id_transaction' 	=> 	$transaction_id,
					'zipcode'			=> 	$transaction->getShipping()->getAddress()->getPostalCode(),
					'street'			=>	$transaction->getShipping()->getAddress()->getStreet(),
					'number' 			=>	$transaction->getShipping()->getAddress()->getNumber(),
					'complement'		=>	$transaction->getShipping()->getAddress()->getComplement(),
					'city'				=>	$transaction->getShipping()->getAddress()->getCity(),
					'state'				=>	$transaction->getShipping()->getAddress()->getState(),
					'district'			=>	$transaction->getShipping()->getAddress()->getDistrict(),
					'country'			=>	$transaction->getShipping()->getAddress()->getCountry(),
					);

					//MONTA O ARRAY COM O TIPO DE PAGAMENTO
					$payment = array(
					'id_transaction' => $transaction_id,
					'id_payment' => $transaction->getPaymentMethod()->getCode()->getValue(), 
					);

					//PERSISTE OS DADOS DA TRANSAÇÃO
					$transactionBusiness->newTransaction($data);

					//PERSISTE OS DADOS DO PAGAMENTO
					$transactionBusiness->savePaymentType($payment);

					//PERSISTE OS DADOS DA ENTREGA
					$transactionBusiness->saveTransactionAddress($transactionAdrress);

					//FAZ A ITERAÇÃO DOS ITENS CONTIDOS NA TRANSAÇÃO
					foreach ($transaction->getItems() as $item){
						
						//MONTA UM ARRAY COM OS PRODUTOS CONTIDOS NA TRANSAÇÃO
						$dataProd = array(
					'id_transaction' => $transaction_id,
					'id_product' => $item->getId(),
						);

						//FAZ UMA REPLICA DO CARRINHO DE COMPRAS DA TRANSAÇÃO
						$cartMirror = array(
					'id_transaction' => $transaction_id,
					'id_product' => $item->getId(),
					'id_client' => $client["id_client"],
					'qtd' => $item->getQuantity(),
						);

						//PERSISTE OS PRODUTOS
						$transactionBusiness->saveProducts($dataProd);

						//PERSISTE A REPLICA DO CARRINHO DE COMPRAS
						$transactionBusiness->saveCartMirror($cartMirror);
					}

					LogPagSeguro::info("Removendo itens do carrinho cliente:".$client['id_client']);
					$cartBusiness->dropCart($client['id_client']);

					LogPagSeguro::info("Ttransação :".$transaction_id." inserida com sucesso");
				}
			}
		}catch(Exception $e){
			echo $e;
		}
	}

}